<template>
  <div class="micro-application" v-loading="loading" element-loading-text="加载中...">
    <!--suppress HtmlUnknownTag -->
    <micro-app
      v-if="config.name"
      :name="config.name"
      :url="config.url"
      :baseroute="config.baseRoute"
      :data="config.data"
      @created='loading=true'
      @mounted='loading=false'
      @error="loadError"
      @datachange="handleDataChange"
    />
  </div>
</template>

<script lang="ts" setup>
import { onUnmounted, reactive, ref, watchPostEffect } from 'vue'
import { microAppConfigs } from '@/config/micro-config'
import { useRoute, useRouter } from 'vue-router'
import eventBus from '@/utils/eventBus'
import { ElMessage } from 'element-plus'
import { useStore } from 'vuex'

const store = useStore()
const route = useRoute()
const router = useRouter()
const loading = ref(false)
const config = reactive({
  name: '',
  url: '',
  baseRoute: '',
  data: {}
})

const loadMicroApp = () => {
  const client = microAppConfigs.find(v => route.path.indexOf(v.publicPath) === 0)
  if (client) {
    config.name = client.name
    config.url = client.url
    config.baseRoute = client.publicPath
  } else {
    ElMessage.error('当前应用配置不存在！')
  }
}
const loadError = () => {
  ElMessage.error('加载应用失败，请检查服务是否正常！')
}
const handleToggle = (data: boolean) => {
  config.data = { type: 'toggle', value: data }
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const handleDataChange = (evt: any) => {
  const data = evt.detail.data
  if (data && data.type === 'pushState') {
    router.push(data.value)
  }
  if (data && data.type === 'crumbsChange') {
    store.dispatch('breadcrumb/setPathOptions', data.value)
  }
}

watchPostEffect(() => {
  loadMicroApp()
})
eventBus.on('toggleChange', handleToggle)
onUnmounted(() => {
  eventBus.off('toggleChange', handleToggle)
})
</script>

<style lang="less">
.micro-application {
  height: 100%;
}
.multiple-tab + .micro-application {
  height: calc(100% - 44px);
}
</style>
